const app = getApp();
import api from "../../../../common/api";
import util from "../../../../utils/util";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvasWidth: 0,
    canvasHeight: 0,
    selectTmpID: '',
    paintPallette: {},
    posterData: {},
    isHidePage: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let t = this;
    t.initSystemInfo()
    t.initData(options)
    t.loadPosterData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  initData(options) {
    let t = this
    t.myData = {
      currentClickBtn: '',
      posterTmp: app.globalData.posterTmp || {},
    }

    t.setData({
      houseID: options.houseid || '',
      selectTmpID: t.myData.posterTmp.tmpID || '',
    })
    t.myData.currentSubCom = t.selectComponent(`.${t.myData.posterTmp.tmpID}`)
  },

  initSystemInfo() {
    let t = this
    wx.getSystemInfo({
      success: function (res) {
        t.setData({
          canvasWidth: res.windowWidth,
          canvasHeight: res.windowHeight
        })
      }
    })
  },

  onDrawSuccess(e) {
    let t = this
    wx.hideLoading()
    let img = e.detail.path
    if (img && typeof img === 'string') {
      if (t.myData.currentClickBtn === 'save') {
        wx.saveImageToPhotosAlbum({
          filePath: img,
          success(res) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
            })
          },
          fail: () => {
            wx.getSetting({
              success: (res) => {
                if (!res.authSetting['scope.writePhotosAlbum']) {
                  wx.showModal({
                    title: '提示',
                    content: '需要获取图片权限哦',
                    success: (res) => {
                      if (res.confirm) {
                        wx.openSetting()
                      }
                    }
                  })
                }
              }
            })
          }
        });
      }
      if (t.myData.currentClickBtn === 'share') {
        wx.previewImage({
          current: img, // 当前显示图片的http链接
          urls: [img], // 需要预览的图片http链接列表
        }, true)
      }
    } else {
      wx.showToast({
        title: '海报制作失败，请稍后再试！',
        icon: 'none',
      })
    }
  },

  onDrawFail() {
    wx.hideLoading()
    wx.showToast({
      title: '海报制作失败，请稍后再试！',
      icon: 'none',
    })
  },

  onSaveImg() {
    let t = this
    wx.showLoading({
      mask: true,
      title: '海报制作中...',
    })
    t.myData.currentClickBtn = 'save'
    t.startDrawPoster()
  },

  onShareImg() {
    let t = this
    wx.showLoading({
      mask: true,
      title: '海报制作中...',
    })
    t.myData.currentClickBtn = 'share'
    t.startDrawPoster()
  },

  startDrawPoster() {
    let t = this
    t.myData.currentSubCom.transmitPosterConfig()
    t.setData({
      paintPallette: t.posterConfig || {}
    })
  },

  getPosterConfig(e) {
    let t = this
    t.posterConfig = e.detail
  },

  loadHouseInfo(id) {
    let t = this;
    return new Promise((resolve, reject) => {
      api.getHouseInfo({
          houDelId: id,
        },
        (res) => {
          if (res && res.data && res.data.isSuccess) {
            let {
              houImageVO = [],
                jjrVO = {},
                houDelVO = {}
            } = res.data.content || {}

            let houseType = houDelVO.delegationType

            let houseInfo = {
              price: '',
              priceLabel: '',
              img: houImageVO.map((item) => {
                return item.url
              }),
              room: houDelVO.room && houDelVO.room != -1 ? houDelVO.room + '室' : '',
              hall: houDelVO.hall && houDelVO.hall != -1 ? houDelVO.hall + '厅' : '',
              structure: '',
              roomLabel: '居室',
              area: houDelVO.buildSize && houDelVO.buildSize != -1 ? houDelVO.buildSize + '㎡' : '--',
              areaLabel: '面积',
              name: houDelVO.resblockName || '',
              address: houDelVO.area || '',
            }

            let userInfo = {
              avatar: jjrVO.avatar || '',
              name: jjrVO.realname || '',
              phone: jjrVO.mobile || '',
            }

            switch (houseType) {
              case 'SALES':
                if (houDelVO.totalPrices && houDelVO.totalPrices != -1) {
                  houseInfo.price = `${houDelVO.totalPrices / 10000}万`
                } else {
                  houseInfo.price = '--'
                }
                houseInfo.priceLabel = '总价'
                break;
              case 'RENT':
                if (houDelVO.totalPrices && houDelVO.totalPrices != -1) {
                  houseInfo.price = `${houDelVO.totalPrices}元/月`
                } else {
                  houseInfo.price = '--'
                }
                houseInfo.priceLabel = '租价'
                break;
              default:
                if (houDelVO.totalPrices && houDelVO.totalPrices != -1) {
                  houseInfo.price = `${houDelVO.totalPrices / 10000}万`
                } else {
                  houseInfo.price = '--'
                }
                houseInfo.priceLabel = '总价'
            }

            if (houseInfo.room || houseInfo.hall) {
              houseInfo.structure = `${houseInfo.room}${houseInfo.hall}`
            } else {
              houseInfo.structure = '--'
            }

            resolve({
              houseInfo,
              userInfo,
            })

          } else {
            resolve({})
          }
        }
      );
    })
  },

  // loadUserInfo() {
  //   let t = this;
  //   return new Promise((resolve, reject) => {
  //     resolve()
  //   })
  // },

  loadPosterData() {
    let t = this
    let {
      houseID
    } = t.data
    Promise.all([t.loadHouseInfo(houseID), t.loadQCode(houseID)])
      .then((res) => {
        t.setData({
          isHidePage: false,
          posterData: {
            bgImg: t.myData.posterTmp.bgImg || '',
            houseInfo: res[0].houseInfo || {},
            userInfo: res[0].userInfo || {},
            qrCode: res[1] || ''
          }
        })
      })
  },

  loadQCode(houseID) {
    let t = this
    return new Promise((resolve, reject) => {
      let loginUserInfo = getApp().globalData.loginUserInfo;
      let sessionUser = loginUserInfo.data.content.sessionUser;
      let param = {
        houDelId: houseID,
        agentId: sessionUser.id,
        storeId: sessionUser.extProps.storeId,
        mkId: "EMP",
        realName: sessionUser.realName,
        mobile: sessionUser.mobile,
      }
      api.qrcodeLongToShort(JSON.stringify(param), {}, (res) => {
        let shortCode = res.data.content;
        let qrCode = `${util.domain}miniCode/getWXACodeUnlimit?page=${encodeURI('pages/houseShare/RentalHouseDetailLite/RentalHouseDetailLite')}&scene=${shortCode}&miniName=zhaofangjs`
        resolve(qrCode)
      })
    })
  },

})